<template>
  <div>
    <h2>Register</h2>

    <el-form :model="form" :rules="rules" ref="formRef" label-width="auto" style="max-width: 600px">
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" show-password />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" show-password />
      </el-form-item>
      <el-form-item label="验证码" v-if="emailValidated" prop="code">
        <el-input v-model="form.code">
          <template #append>
            <el-button :disabled="isSending" @click="sendCode">{{ buttonText }}</el-button>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item>
        <div class="div1">

          <div class="left">
            <el-button @click="goTo('/user/login')">已有账号？去登录</el-button>
          </div>
          <div class="right"> <el-button type="primary" @click="submitForm">确认</el-button>
          </div>
        </div>

      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import axios from 'axios';
import { FormRules } from 'element-plus';


// do not use same name with ref
const form = reactive({
  email: '',
  name: '',
  password: '',
  confirmPassword: '',
  code: '',

})


import { useGoTo } from '@/hooks/useGoTo';
const { goTo } = useGoTo()

const formRef = ref(null);
const emailValidated = ref(false);
const countdown = ref(0);
const isSending = ref(false);
let countdownInterval: ReturnType<typeof setInterval> | null = null;

const rules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && value.trim() !== '') {
          // 假设邮箱格式正确且不为空，则验证通过  
          emailValidated.value = true;
          callback();
        } else {
          emailValidated.value = false;
          callback(new Error('请输入有效的邮箱地址'));
        }
      },
      trigger: 'change'
    }
  ],
  name: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: checkPassword, trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为 6 位', trigger: 'blur' },
  ],
};

function checkPassword(rule: any, value: string, callback: any) {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
}


const submitForm = () => {
  if (formRef.value) {
    formRef.value.validate((valid) => {
      if (valid) {
        onSubmit();

      } else {
        ElMessage({
          message: '验证失败',
          grouping: true,
          type: 'error',
        });
        return false;
      }
    });
  }
};




async function sendCode() {
  if (!isSending.value) {
    isSending.value = true;
    startCountdown();
    try {
      const params = {
        email: form.email
      }
      const response = await axios.get('/api/user/sendCode', { params });
      // 处理响应，例如导航到主页面或更新状态    
      console.log(response.data);

      if (response.data.code === '200') {
        ElMessage({
          message: '发送成功',
          type: 'success',
        })
      } else if (response.data.code === '-1') {
        ElMessage({
          message: response.data.msg,
          type: 'error',
        })
      }

    } catch (error) {
      // 处理错误，例如显示错误消息给用户    
      console.error(error);
      // 可以使用 alert 或其他 UI 库来显示错误消息  
    }
  }
}

const startCountdown = () => {
  countdown.value = 60;
  countdownInterval = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownInterval!);
      countdownInterval = null;
      isSending.value = false;
    }
  }, 1000);
};

const buttonText = computed(() => {
  return isSending.value ? `${countdown.value}秒后重发` : '发送验证码';
});



async function onSubmit() {
  try {
    const response = await axios.post('/api/user/insert', {
      email: form.email,
      username: form.name,
      password: form.password,
      code: form.code,
    });

    // 处理响应，例如导航到主页面或更新状态    
    console.log(response.data);
    console.log(`${form.email} ${form.password}`); // 使用模板字符串来连接字符串  
    if (response.data.code === '200') {
      ElMessage({
        message: '提交成功',
        type: 'success',
      })
      goTo('/user/login')
    } else if (response.data.code === '-1') {
      ElMessage({
        message: response.data.msg,
        type: 'error',
      })
    }

  } catch (error) {

    console.error(error);

  }
}

onUnmounted(() => {
  if (countdownInterval) {
    clearInterval(countdownInterval);
  }
});

</script>

<style scoped>
.div1 {
  width: 1200px;
  height: 70px;
  display: flex;
  justify-content: space-between;
}

.left {
  display: flex;
  justify-content: center;
  align-items: center;
}

.right {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>